package com.wys.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wys.common.utils.HttpUtils;
import com.wys.mall.member.dao.MemberLevelDao;
import com.wys.mall.member.entity.MemberLevelEntity;
import com.wys.mall.member.exception.PhoneExistException;
import com.wys.mall.member.exception.UserExistException;
import com.wys.mall.member.vo.SocialUser;
import com.wys.mall.member.vo.UserLoginVo;
import com.wys.mall.member.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wys.common.utils.PageUtils;
import com.wys.common.utils.Query;

import com.wys.mall.member.dao.MemberDao;
import com.wys.mall.member.entity.MemberEntity;
import com.wys.mall.member.service.MemberService;


@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public void regist(UserRegisterVo vo) {
        MemberEntity entity = new MemberEntity();
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setCreateTime(new Date());
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(passwordEncoder.encode(vo.getPassword()));
//        System.out.println(passwordEncoder.matches("123456","$2a$10$FyXeHBTXUCRqerg5rHEgSOm1NyT0Y.RBMzVWFHNRJWLb6geyOwRZm"));
        this.save(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phoneCount > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserExistException {
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (usernameCount > 0) {
            throw new UserExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String account = vo.getLoginAcct();
        String password = vo.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>().eq("username", account).or().eq("mobile", account);
        MemberEntity entity = this.baseMapper.selectOne(queryWrapper);
        if (entity == null) {
            //登录失败
            return null;
        }
        //密码对比
        boolean matches = passwordEncoder.matches(password, entity.getPassword());
        if (matches) {
            return entity;
        }
        return null;

    }

    /**
     * 社交登录与注册
     *
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //社交帐号id
        String uid = socialUser.getUid();
        //判断是否登录过
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        if (memberEntity != null) { //说明已经注册了
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity);
            return memberEntity;
        } else {
            MemberEntity register = new MemberEntity();
            try{
                //3、查询当前社交用户的社交账号信息（昵称、性别等）
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");

                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setHeader(profileImageUrl);
                }
            }catch (Exception e){

            }
            register.setCreateTime(new Date());
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            //把用户信息插入到数据库中
            this.baseMapper.insert(register);

            return register;
        }
    }

}